package com.huiyin.ui.user;

import java.io.File;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.huiyin.R;
import com.huiyin.UIHelper;
import com.huiyin.base.BaseActivity;
import com.huiyin.utils.AppManager;
import com.huiyin.utils.DialogUtil;
import com.huiyin.utils.FileUtils;
import com.huiyin.utils.ImageManager;
import com.huiyin.utils.StringUtils;
import com.huiyin.utils.UPYunUploadUtil;
import com.huiyin.utils.UPYunUploadUtil.UploadListener;
import com.huiyin.utils.imageupload.ImageFolder;
import com.huiyin.wight.Tip;
/**
 * 填写身份证信息弹出框
 * @author zhyao
 *
 */
public class IdentificationActivityDialog extends BaseActivity implements OnClickListener {
	
	protected static final String TAG = "IdentificationActivityDialog";

	/** 相册 **/
	private static final int REQUEST_CODE_PICK_IMAGE = 0;

	/** 照相 **/
	private static final int REQUEST_CODE_CAPTURE_CAMEIA = 1;
	
	/** 上传身份证正面 **/
	private static final int SELECT_IDENTIFICATION_POSITIVE = 0;
	
	/** 上传身份证反面 **/
	private static final int SELECT_IDENTIFICATION_INVERSE = 1;
	
	/** 是否已实名认证 **/
	public static final String INTENT_KEY_IS_CERTIFICATION = "isCertification";
	
	/** 身份证号码 **/
	public static final String INTENT_KEY_IDENTIFICATION_CODE = "identificationCode";
	
	/** 身份证正面地址 **/
	public static final String INTENT_KEY_IDENTIFICATION_POSITIVE = "identificationPositiveUrl";
	
	/** 身份证反面地址 **/
	public static final String INTENT_KEY_IDENTIFICATION_INVERSE = "identificationInverseUrl";

	/** 身份证信息填写成功返回code **/
	public static final int RESULT_CODE = 1000;

	/** 取消 **/
	private ImageView mCancelImg;
	
	/** 身份证号 **/
	private EditText mIdentificationEdt;
	
	/** 身份证正面 **/
	private ImageView mIdentificationPositiveImg;
	
	/** 身份证反面 **/
	private ImageView mIdentificationInverseImg;
	
	/** 重新上传 **/
	private TextView mReloadupPositiveTv;
	
	/** 重新上传 **/
	private TextView mReloadupInverseTv;
	
	/** 确定 **/
	private Button mSureBtn;
	
	/** 身份证号码**/
	private String identificationCode;
	
	/** 身份证正面地址 **/
	private String identificationPositiveUrl;
	
	/** 身份证反面地址 **/
	private String identificationInverseUrl;
	
	/**当前照片的文件**/
	//private File imageFile;
	
	/** 照相机拍照保存的路径 **/
	private String mCameraCapturePath = null;
	
	/** 身份证当前选择 **/
	private int selectIdentification = SELECT_IDENTIFICATION_POSITIVE;

	@SuppressWarnings("static-access")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.popup_identification);
		
		identificationCode = getIntent().getStringExtra(IdentificationActivityDialog.INTENT_KEY_IDENTIFICATION_CODE);
		identificationPositiveUrl = getIntent().getStringExtra(IdentificationActivityDialog.INTENT_KEY_IDENTIFICATION_POSITIVE);
		identificationInverseUrl = getIntent().getStringExtra(IdentificationActivityDialog.INTENT_KEY_IDENTIFICATION_INVERSE);
		initView();
		
		
		WindowManager.LayoutParams lp = getWindow().getAttributes();
		lp.width = lp.MATCH_PARENT;
		lp.height = lp.WRAP_CONTENT;
		lp.gravity = Gravity.BOTTOM;
		getWindow().setAttributes(lp);
	}

	private void initView() {
		mCancelImg = (ImageView) findViewById(R.id.img_cancel);
		mIdentificationEdt = (EditText) findViewById(R.id.edt_identification);
		mIdentificationPositiveImg = (ImageView) findViewById(R.id.img_identification_positive);
		mIdentificationInverseImg = (ImageView) findViewById(R.id.img_identification_inverse);
		mReloadupPositiveTv = (TextView) findViewById(R.id.tv_reloadup_positive);
		mReloadupInverseTv = (TextView) findViewById(R.id.tv_reloadup_inverse);
		mSureBtn = (Button) findViewById(R.id.btn_sure);
		
		if(!StringUtils.isEmpty(identificationCode)) {
			mIdentificationEdt.setText(identificationCode);
		}
		
		if(!StringUtils.isEmpty(identificationPositiveUrl)) {
			ImageManager.Load(identificationPositiveUrl, mIdentificationPositiveImg);
			mReloadupPositiveTv.setVisibility(View.VISIBLE);
		}
		
		if(!StringUtils.isEmpty(identificationInverseUrl)) {
			ImageManager.Load(identificationInverseUrl, mIdentificationInverseImg);
			mReloadupInverseTv.setVisibility(View.VISIBLE);
		}
		
		mCancelImg.setOnClickListener(this);
		mIdentificationPositiveImg.setOnClickListener(this);
		mIdentificationInverseImg.setOnClickListener(this);
		mSureBtn.setOnClickListener(this);
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		//取消
		case R.id.img_cancel:
			AppManager.getAppManager().finishActivity();
			overridePendingTransition(R.anim.popwindow_in, R.anim.popwindow_out);
			break;
		//上传身份证正面
		case R.id.img_identification_positive:
			selectIdentification = SELECT_IDENTIFICATION_POSITIVE;
			showPictureSelectDialog();
			break;
		//上传省份证反面
		case R.id.img_identification_inverse:
			selectIdentification = SELECT_IDENTIFICATION_INVERSE;
			showPictureSelectDialog();
			break;
		//确定
		case R.id.btn_sure:
			
			identificationCode = mIdentificationEdt.getText().toString().trim();
			
			if(!StringUtils.isIdentification(identificationCode)) {
				UIHelper.showToast("请输入正确的身份证号");
				return;
			}
			
			if(StringUtils.isEmpty(identificationPositiveUrl) || StringUtils.isEmpty(identificationInverseUrl)) {
				UIHelper.showToast("请上传身份证");
				return;
			}
			
			Intent data = new Intent();
			data.putExtra(INTENT_KEY_IDENTIFICATION_CODE, identificationCode);
			data.putExtra(INTENT_KEY_IDENTIFICATION_POSITIVE, identificationPositiveUrl);
			data.putExtra(INTENT_KEY_IDENTIFICATION_INVERSE, identificationInverseUrl);
			setResult(RESULT_CODE, data);
			AppManager.getAppManager().finishActivity();
			overridePendingTransition(R.anim.popwindow_in, R.anim.popwindow_out);
			break;

		default:
			break;
		}
		
	}
	

	/**
	 * 选择图片的方式对话框
	 */
	private void showPictureSelectDialog() {

		DialogUtil.showPictureSelectDialog(mContext, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				// 相册
				case 0:
					getImageFromAlbum();
					break;
				// 照相
				case 1:
					getImageFromCamera();
					break;

				default:
					break;
				}
			}
		});

	}
	
	/**
	 * 相册获取图片
	 */
	private void getImageFromAlbum() {
		
//		Intent intent = new Intent(Intent.ACTION_PICK);
//		intent.setType("image/*");// 相片类型
//		imageFile = ImageFolder.getTempImageName();
//		intent.putExtra("crop", "true"); // 开启剪切
//		intent.putExtra("aspectX", 86); // 剪切的宽高比
//		intent.putExtra("aspectY", 54);
//		intent.putExtra("outputX", 860); // 保存图片的宽和高
//		intent.putExtra("outputY", 540);
//		intent.putExtra("output", Uri.fromFile(imageFile)); // 保存路径
//		intent.putExtra("outputFormat", "JPEG");// 返回格式
//		startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
		
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType("image/*");// 相片类型
		startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
		
	}

	
	/**
	 * 拍照获取图片
	 */
	private void getImageFromCamera() {
//		String state = Environment.getExternalStorageState();
//		if (state.equals(Environment.MEDIA_MOUNTED)) {
//			imageFile = ImageFolder.getTempImageName();
//			Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//			Uri uri = Uri.fromFile(imageFile);
//			captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
//			captureIntent.putExtra("return-data", true);
//			startActivityForResult(captureIntent, REQUEST_CODE_CAPTURE_CAMEIA);
//			
//		} else {
//			UIHelper.showToast("请确认已经插入SD卡");
//		}
		
		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			Intent getImageByCamera = new Intent("android.media.action.IMAGE_CAPTURE");
			mCameraCapturePath = ImageFolder.getTempImageName().getPath();
			getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraCapturePath)));
			startActivityForResult(getImageByCamera, REQUEST_CODE_CAPTURE_CAMEIA);
		} else {
			UIHelper.showToast("请确认已经插入SD卡");
		}
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// 相册
		if (requestCode == REQUEST_CODE_PICK_IMAGE && resultCode == RESULT_OK) {
			//setIdentificationImg(imageFile.getAbsolutePath());
			if (data == null || "".equals(data)) {
				// 相册没有图片
				UIHelper.showToast("没有选择图片");
				return;
			}
			Uri selectedImage = FileUtils.geturi(data, this);
			String[] filePathColumns = { MediaStore.Images.Media.DATA };
			Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
			if(c != null) {
				c.moveToFirst();
				int columnIndex = c.getColumnIndex(filePathColumns[0]);
				String picturePath = c.getString(columnIndex);
				c.close();
				setIdentificationImg(picturePath);
			}
		}
		// 照相机
		else if (requestCode == REQUEST_CODE_CAPTURE_CAMEIA && resultCode == RESULT_OK) {
//			//相机拍照，返回，再跳转到裁剪界面
//			Intent intent = new Intent("com.android.camera.action.CROP");
//			intent.setDataAndType(Uri.fromFile(imageFile), "image/*");
//			intent.putExtra("crop", "true"); // 开启剪切
//			intent.putExtra("aspectX", 86); // 剪切的宽高比
//			intent.putExtra("aspectY", 54);
//			intent.putExtra("outputX", 860); // 保存图片的宽和高
//			intent.putExtra("outputY", 540);
//			intent.putExtra("noFaceDetection", false);
//			intent.putExtra("scale", true);
//			imageFile = ImageFolder.getTempImageName();
//			intent.putExtra("output", Uri.fromFile(imageFile));
//			intent.putExtra("outputFormat", "JPEG");// 返回格式
//			startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
			if (data == null || "".equals(data)) {
				File f = new File(mCameraCapturePath);
				if (!f.exists()) {
					return;
				} else {
					setIdentificationImg(mCameraCapturePath);
					return;
				}
			}
			
		}

		super.onActivityResult(requestCode, resultCode, data);

	}
	
	/**
	 * 设置身份证图片
	 * @param imgPath
	 */
	private void setIdentificationImg(String imgPath) {
		if(selectIdentification == SELECT_IDENTIFICATION_POSITIVE) {
			ImageManager.Load("file://"+imgPath, mIdentificationPositiveImg);
			mReloadupPositiveTv.setVisibility(View.VISIBLE);
		}
		else if (selectIdentification == SELECT_IDENTIFICATION_INVERSE) {
			ImageManager.Load("file://"+imgPath, mIdentificationInverseImg);
			mReloadupInverseTv.setVisibility(View.VISIBLE);
		}
		
		upLoadImage(imgPath);
		
	}

	/**
	 * 上传身份证图片
	 * @param imgPath
	 */
	private void upLoadImage(String imgPath) {
		Tip.showLoadDialog(this, getString(R.string.loading));
		UPYunUploadUtil mUploadUtil = new UPYunUploadUtil(this);
		mUploadUtil.uploadFile(imgPath, new UploadListener() {
			
			@Override
			public void onSuccess(String upYunBackUrl) {
				Log.d(TAG, "uploadPictures onSuccess　: upYunBackUrl = " + upYunBackUrl);
				Tip.colesLoadDialog();
				
				if(selectIdentification == SELECT_IDENTIFICATION_POSITIVE) {
					identificationPositiveUrl = upYunBackUrl;
				}
				else if (selectIdentification == SELECT_IDENTIFICATION_INVERSE) {
					identificationInverseUrl = upYunBackUrl;
				}
				
			}
			
			@Override
			public void onFail() {
				Tip.colesLoadDialog();
				UIHelper.showToast("上传图片失败");
				return;
			}
		});
	}

	
}
